package com.ada;

import org.apache.commons.codec.binary.Base64;
import sun.font.FontDesignMetrics;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;

public class HaiBao {

    public static void main(String[] args) {
        String backgroundPath = "https://hcpj.oss-cn-shanghai.aliyuncs.com/common//console/33e4ffb8-03f8-428d-be80-32dfc8804311.png";
        String qrCodePath = "https://zgyx-innoarm.obs.cn-north-4.myhuaweicloud.com/billCloud/qr.png";
        String people_img="https://zgyx-innoarm.obs.cn-north-4.myhuaweicloud.com/billCloud/qr.png";
        String message01 ="我是婓曼妮，正在参加投票活动正在参加投票活动，快来为我投票吧。o(^▽^)o";
        String message02 = "婓曼妮";
        String outPutPath="D:\\qr1.jpg";
        overlapImage(backgroundPath,qrCodePath,people_img,message01,message02,outPutPath);
    }
    //BufferedImage 转base64
    public String GetBase64FromImage(BufferedImage img){
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            // 设置图片的格式
            ImageIO.write(img, "jpg", stream);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] bytes = Base64.encodeBase64(stream.toByteArray());
        String base64 = new String(bytes);
        return  "data:image/jpeg;base64,"+base64;
    }

    public static String overlapImage(String backgroundPath,String qrCodePath,String people_img,String message01,String message02,String outPutPath){
        int width=800;
        int height=1000;
        try {
            BufferedImage bg = ImageIO.read(getFile(backgroundPath));
            height=width*bg.getHeight()/bg.getWidth();
            //设置图片大小
            BufferedImage background = resizeImage(width,height, bg);

            BufferedImage qrCode = resizeImage(150,150,ImageIO.read(getFile(qrCodePath)));
            BufferedImage peopleImg = resizeImage(550,750,ImageIO.read(getFile(people_img)));
            //在背景图片中添加入需要写入的信息，例如：扫描下方二维码，欢迎大家添加我的淘宝返利机器人，居家必备，省钱购物专属小秘书！
            Graphics2D g = background.createGraphics();
            g.setColor(Color.white);
            g.setFont(new Font("微软雅黑",Font.BOLD,35));

            // 计算文字长度，计算居中的x点坐标
            Font font=new Font("微软雅黑",Font.BOLD,35);



            FontMetrics fm = g.getFontMetrics(font);
            int textWidth = fm.stringWidth(message02);
            int widthX = (width - textWidth) / 2;
           // g.drawString(message02,widthX ,50);




            int fontsize2=25;
            g.setFont(new Font("微软雅黑",Font.BOLD,fontsize2));
            Font font1=new Font("微软雅黑",Font.BOLD,fontsize2);
//            FontMetrics f1 = g.getFontMetrics(font1);
//            int textWidth1 = f1.stringWidth(message01);
//            System.out.printf("字体宽度--"+textWidth1+"字符数--"+message01.length());
//            int widthX1 = (width - textWidth1) / 2;
//            g.drawString(message01,widthX1 ,100);

            //int bottomY= drawWordAndLineFeed(g,font1,message01,50,100,600);


           // g.drawImage(peopleImg, 75, bottomY, peopleImg.getWidth(), peopleImg.getHeight(), null);
            int y = height - qrCode.getHeight() -35;
            int x=(width-qrCode.getWidth())/2;

            //在背景图片上添加二维码图片
            g.drawImage(qrCode, x, y, qrCode.getWidth(), qrCode.getHeight(), null);
            g.dispose();
            System.out.printf("outPutPath"+outPutPath);
            ImageIO.write(background, "jpg", new File(outPutPath));
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    private static int drawWordAndLineFeed(Graphics2D g2d, Font font, String words, int wordsX, int wordsY, int wordsWidth) {
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(font);
        // 获取字符的最高的高度
        int height = metrics.getHeight();

        int width = 0;
        int count = 0;
        int total = words.length();
        System.out.println("几行字--"+total);
        String subWords = words;
        int b = 0;

        int zuidi=0;

        for (int i = 0; i < total; i++) {
            // 统计字符串宽度 并与 预设好的宽度 作比较
            if (width <= wordsWidth) {
                width += metrics.charWidth(words.charAt(i)); // 获取每个字符的宽度
                count++;
            } else {
                // 画 除了最后一行的前几行
                String substring = subWords.substring(0, count);
                g2d.drawString(substring, wordsX, wordsY + (b * height));
                subWords = subWords.substring(count);
                b++;
                width = 0;
                count = 0;
            }
            // 画 最后一行字符串
            if (i == total - 1) {
                g2d.drawString(subWords, wordsX, wordsY + (b * height));
            }
            zuidi=wordsY + (b * height);
        }
        System.out.println("高度--"+zuidi+25);
        return zuidi+25;
    }

    private static File getFile(String url) throws Exception {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."),url.length());
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return file;
    }

    public static BufferedImage resizeImage(int x, int y, BufferedImage bfi){
        BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
        bufferedImage.getGraphics().drawImage(
                bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
        return bufferedImage;
    }
}
